/*
 * 1.根据Select组件，在不搜索时，实现分页加载（滚动加载）
    2.远程根据关键字搜索
 */
import React, { useEffect, useState, useRef } from 'react';
import { Select, Spin } from 'antd';
import { FrownOutlined } from '@ant-design/icons';
import debounce from 'lodash/debounce';
import { getFamilyListApi } from '../../api/index';
const { Option } = Select;
const App = () => {
    const [options, setOptions] = useState([]);
    const [loadingMore, setLoadingMore] = useState(false);
    const [allLoaded, setAllLoaded] = useState(false);
    const [keyWord, setKeyword] = useState(null);
    const curPage = useRef(1);

    const handleScroll = (e) => {
        const {scrollTop, offsetHeight, clientHeight, scrollHeight} = e.target;
        if (scrollTop + offsetHeight >= scrollHeight && !allLoaded && !loadingMore) {
            setLoadingMore(true);
            curPage.current += 1;
            const params = {
                pageNum: curPage.current,
                pageSize: 15,
            }
            if (keyWord) {
                params.keyword = keyWord;
            }
            getFamilyListApi(params).then(res => {
                if (res.code === '000') {
                    const list = res?.data?.data || [];
                    const newOptions = list.map((item) => {
                        return {
                            familyName: item.familyName ? item.familyName.slice(0,10) : '--',
                            value: item.familyId,
                            accountPhone: item.accountPhone ? item.accountPhone : '--',
                            remarks: item.remarks ? item.remarks.slice(0,10) : '--',
                        }
                    })

                    if (list.length > 0) {
                        setOptions((prevOptions) => [...prevOptions, ...newOptions]);
                    } else  {
                        setAllLoaded(true);
                        curPage.current = 1;
                    }
                }
            }).finally(() => {
                setLoadingMore(false);
            })
        }
    }
    // 首次加载请求数据
    useEffect(() => {
        init();
    }, []);

    const init = () => {
        getFamilyListApi({
            pageNum: 1,
            pageSize: 15
        }).then(res => {
            if (res.code === '000') {
                const list = res?.data?.data || [];
                const newOptions = list.map((item) => ({
                    familyName: item.familyName ? item.familyName.slice(0,10) : '--',
                    value: item.familyId,
                    accountPhone: item.accountPhone ? item.accountPhone : '--',
                    remarks: item.remarks ? item.remarks.slice(0,10) : '--',
                }));
                if (list.length > 0) {
                    setOptions(newOptions);
                } else {
                    setAllLoaded(true);
                    curPage.current = 1;
                }
            }
        }).finally(() => {
            setLoadingMore(false);
        })
    }

    
    const remoteMethod = (query) => {
        if (!query) return
        setKeyword(query.trim())
        setLoadingMore(true)
        setAllLoaded(false)
        const params = {
            keyword: query.trim(),
            pageNum: curPage.current,
            pageSize: 15,
        }
        getFamilyListApi(params).then(res => {
            if (res.code === '000') {
                const list = res?.data?.data || []
                
                const newOptions = list.map(item => {
                    return {
                        familyName: item.familyName ? item.familyName.slice(0,10) : '--',
                        value: item.familyId,
                        accountPhone: item.accountPhone ? item.accountPhone : '--',
                        remarks: item.remarks ? item.remarks.slice(0,10) : '--',
                    }
                });
                console.log(newOptions, 'newOptions查询')
                setOptions(newOptions);
            }
        }).finally(() => {
            setLoadingMore(false);
        })
    }

    const remoteMethodDebounce = debounce(remoteMethod, 500)
    const handleOnSearch = (val) => {
        // 文本框值变化时回调
        console.log(val, '文本框值变化时回调')
        // 输入值发生变化马上将当前页数重置为1
        curPage.current = 1;
        remoteMethodDebounce(val);
    }
    // 失去焦点的回调
    const handleOnblur = () => {
        // 去除kewWord
        setKeyword(null)
        // 重置当前页数
        curPage.current = 1;
        // 重置loadingMore
        setLoadingMore(false)
        // 重置allLoaded
        setAllLoaded(false)
        // 重置options
        init();
    }

    return (
        <>
            <Select
                style={{
                    width: 400,
                }}
                placeholder="输入主账号/设备号/备注搜索"
                filterOption={false}
                notFoundContent={<div style={{textAlign: 'center'}}>暂无数据</div>}
                loading={loadingMore}
                onPopupScroll={handleScroll}
                showSearch
                onSearch={handleOnSearch}
                onBlur={handleOnblur}
                dropdownRender={menu => (
                    <div>
                        <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', height: '40px'}}>
                            <div>主账号</div>
                            <div>家庭名称</div>
                            <div>备注</div>
                        </div>
                        {menu}
                        <div>
                            {loadingMore && !allLoaded ? (
                                <div style={{textAlign: 'center', padding: '10px 0'}}>
                                    <Spin />&emsp;加载中...
                                </div>
                            ): null
                            }
                            {allLoaded ? (
                                <div style={{textAlign: 'center', padding: '10px 0'}}>没有更多了&nbsp;<FrownOutlined /></div>
                            ): null}
                        </div>
                    </div>
                )}
            >
                {options.map(data => (
                    <Option key={data.value} value={data.value}>
                        <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center'}}>
                            <div>{data.accountPhone}</div>
                            <div>{data.familyName}</div>
                            <div>{data.remarks}</div>
                        </div>
                    </Option>
                ))}
            </Select>
        </>

    );
};
export default App;